﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NetCore.Ado;
using NetCore.Model;
namespace NetCore.BLL
{
    public class SerialRuleService : SerivceBase, ISerialRuleService
    {
        #region 属性
        public const string SerialRule_No_Rule = "0004";
        public readonly object locked = new object();
        public static string RootPath{
            get {
                return ApplicationEnvironments.BaseDirectory + ApplicationEnvironments.Site.ConfigFile.configPath + "serialrule/serialno.json"; 
            }
        }
        #endregion
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<SerialRuleEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(SerialRuleEntity.__IsDeleted, false);
            return this.Query<SerialRuleEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public SerialRuleEntity GetById(object id)
        {
            return this.GetById<SerialRuleEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(SerialRuleEntity entity, ref string strError)
        {
            if (string.IsNullOrWhiteSpace(entity.SerialRuleId))
            {
                entity.SerialRuleId = this.CreateSerialNo(SerialRule_No_Rule, null, ref strError);
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<SerialRuleEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq(SerialRuleEntity.__IsDeleted, false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(SerialRuleEntity.__Remark, ligerGrid.keyWord)
                           );
            }
            return this.Query<SerialRuleEntity>(ligerGrid, criter);
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 获取编号方法
        /// </summary>
        /// <param name="serialRuleId">标识</param>
        /// <param name="tableName"></param>
        /// <param name="fieldName"></param>
        /// <param name="dataParams">参数</param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public string CreateSerialNo(string serialRuleId, Dictionary<string, string> dataParams, ref string strError)
        {
            string SerialNo = "";
            string SerialPrefix = "";//前缀
            string SerialSuffix = "";//后缀
           
            if (string.IsNullOrEmpty(serialRuleId))
            {
                return "";
            }
            lock (locked)
            {
                SerialRuleEntity entity = CacheService.GetOrCreate<SerialRuleEntity>(ConfigHelper.GetCacheModelKey(typeof(SerialRuleEntity), serialRuleId), () =>
                {
                    return this.GetById(serialRuleId);
                }, true);
                if (entity == null)
                {
                    return "";
                }
                if (dataParams != null && dataParams.Count > 0)
                {
                    foreach (var key in dataParams.Keys)
                    {
                        if (!string.IsNullOrEmpty(entity.SerialPrefix))
                        {
                            SerialPrefix = entity.SerialPrefix.Replace("【" + key + "】", dataParams[key]);
                        }
                        if (!string.IsNullOrEmpty(entity.SerialSuffix))
                        {
                            SerialSuffix = entity.SerialSuffix.Replace("【" + key + "】", dataParams[key]);
                        }
                    }
                }
                else
                {
                    SerialPrefix = entity.SerialPrefix;
                    SerialSuffix = entity.SerialSuffix;
                }
                SerialNo += entity.IsYear ? DateTime.Now.Year.ToString() : "";
                SerialNo += entity.IsMonth ? DateTime.Now.Month.ToString().PadLeft(2, '0') : "";
                SerialNo += entity.IsDay ? DateTime.Now.AddDays(1).Day.ToString().PadLeft(2, '0') : "";
                SerialNo += entity.IsTime ? DateTime.Now.ToString("HHmmss") : "";
                SerialNo = SerialPrefix + SerialNo + SerialSuffix;
                var valuePairs= this.GetValuePairs();
                string NewSerialNo = SerialNo;
                if (string.IsNullOrWhiteSpace(SerialNo))
                {
                    NewSerialNo = "fristKey";//默认键值
                }
                if (!valuePairs.ContainsKey(serialRuleId))
                {
                    valuePairs[serialRuleId] = new Dictionary<string, int>();
                    entity.SerialCount += 1;
                    valuePairs[serialRuleId].Add(SerialNo, entity.SerialCount);
                }
                else
                {
                    if (valuePairs[serialRuleId] == null )
                    {
                        valuePairs[serialRuleId] = new Dictionary<string, int>();
                        entity.SerialCount += 1;
                        valuePairs[serialRuleId].Add(SerialNo, entity.SerialCount);
                    }
                    else
                    {
                        if (valuePairs[serialRuleId].ContainsKey(NewSerialNo))
                        {
                            valuePairs[serialRuleId][NewSerialNo]=entity.SerialCount = valuePairs[serialRuleId][NewSerialNo]+1;
                        }
                        else
                        {
                            if (entity.IsMonth || entity.IsDay)
                            {
                                valuePairs[serialRuleId] = new Dictionary<string, int>();
                            }
                            entity.SerialCount += 1;
                            valuePairs[serialRuleId].Add(NewSerialNo, entity.SerialCount);
                        }

                    }
                }
                entity.IsUpdated = true;
                this.SaveValuePairs(valuePairs);
               // this.SaveOrUpdate<SerialRuleEntity>(entity);
               // CacheService.AddAsync(ConfigHelper.GetCacheModelKey(typeof(SerialRuleEntity), serialRuleId), entity);
                return SerialNo + entity.SerialCount.ToString().PadLeft(entity.SerialLength, '0');
            }
        }

        public bool SaveValuePairs(Dictionary<string, Dictionary<string, int>> valuePairs)
        {
           
            FileInfo fileInfo = new FileInfo(RootPath);
            if (!fileInfo.Exists)
            {
                if (!fileInfo.Directory.Exists)
                {
                    fileInfo.Directory.Create();
                }
            }
            FileHelper.WriteLine(RootPath, JSONHelper.ToJson(valuePairs));
            return true;
        }

        /// <summary>
        /// 获取最大值
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, Dictionary<string, int>> GetValuePairs()
        {
            Dictionary<string, Dictionary<string, int>> valuePairs = new Dictionary<string, Dictionary<string, int>>();
            FileInfo fileInfo = new FileInfo(RootPath);
            if (!fileInfo.Exists)
            {
                return valuePairs;
            }
            var xmlData= FileHelper.ReadLine(RootPath);
            if (!string.IsNullOrWhiteSpace(xmlData))
            {
                  return  JSONHelper.FromJson<Dictionary<string, Dictionary<string, int>>>(xmlData);
            }
            return valuePairs;
        }

     
        #endregion

    }
}